package com.yigo.bsc.app.service;

import com.yigo.bsc.api.constant.BscCodeEnum;
import com.yigo.bsc.api.dict.command.CreateDictItemCmd;
import com.yigo.bsc.api.dict.command.CreateDictTypeCmd;
import com.yigo.bsc.app.assembler.BscDictDTO2DmoAssembler;
import com.yigo.cuc.domain.dict.entity.DictItem;
import com.yigo.cuc.domain.dict.entity.DictType;
import com.yigo.cuc.domain.dict.repo.DictRepo;
import com.yigo.framework.http.BException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author chenzl105
 */
@Service
public class BscDictAppService {
    @Resource
    private DictRepo dictRepo;

    public void createDictType(CreateDictTypeCmd cmd) {
        Long count = dictRepo.countDictTypeByCodeOrName(cmd.getDictTypeCode(), cmd.getDictTypeName());
        if (count > 0) {
            throw new BException(BscCodeEnum.DICT_TYPE_EXISTS, cmd.getDictTypeCode(), cmd.getDictTypeName());
        }
        DictType dictType = BscDictDTO2DmoAssembler.INSTANCE.toDmo(cmd);
        dictRepo.save(dictType);
    }

    public void createDictItem(CreateDictItemCmd cmd) {
        Long count = dictRepo.countDictItemByTypeCodeAndCodeOrName(cmd.getDictTypeCode(), cmd.getDictItemCode(),
                cmd.getDictItemName());
        if (count > 0) {
            throw new BException(BscCodeEnum.DICT_TYPE_EXISTS, cmd.getDictTypeCode(), cmd.getDictItemName());
        }
        DictItem dictItem = BscDictDTO2DmoAssembler.INSTANCE.toDmo(cmd);
        dictRepo.save(dictItem);
    }
}
